package com.smashcrush.server.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.smashcrush.model.Script;
import com.smashcrush.model.User;
import com.smashcrush.server.service.ScriptService;
import com.smashcrush.server.service.UserService;

@Service("scriptServiceImpl")
@Transactional
public class ScriptServiceImpl implements ScriptService {

	@Autowired
	UserService userService;

	@PersistenceContext
	EntityManager em;

	@Override
	public String saveScript(String token, Script script) {

		// validation

		userService.authorize(token, script);

		em.merge(script);

		return script.getId();
	}

	@Override
	public List<Script> getScripts(String token) {

		User user = userService.findByToken(token);

		Query query = em.createQuery("SELECT o FROM " + Script.class.getName()
				+ " o WHERE o.userId=:userId");
		query.setParameter("userId", user.getId());

		return query.getResultList();
	}

	@Override
	public Script getScript(String token, String name) {

		Query query = em.createQuery("SELECT o FROM " + Script.class.getName()
				+ " o WHERE o.name=:name");
		query.setParameter("name", name);

		return (Script) query.getSingleResult();
	}

}
